package com.dyz.leetcode._08_StackAndQueue;

import java.util.ArrayDeque;

public class _224_calculate {
    public int calculate(String s) {
        ArrayDeque<Integer> stack = new ArrayDeque<>();
        int preSign = 1;
        int num = 0;
        int res = 0;
        for(char c:s.toCharArray()){
            if(c>='0' && c<='9'){
                num = num*10+ (c-'0');
            }
            else if(c=='+'){
                res += (num*preSign);
                preSign = 1;
                num = 0;
            }
            else if(c=='-'){
                res += (num*preSign);
                preSign = -1;
                num = 0;
            }
            else if(c=='('){
                stack.push(res);
                stack.push(preSign);
                res = 0;
                preSign = 1;
                num = 0;

            }else if(c==')'){
                res += (preSign*num);
                res*=stack.pop();
                res+=stack.pop();
                num = 0;
            }
        }
    return res+num*preSign;
    }
}
